//
//  AppDelegate.m
//  PetApp
//
//  Created by apple on 16/3/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AppDelegate.h"
#import "FirstScrollView.h"
#import "DataBaseHandle.h"
#import <DKNightVersion.h>
#import <CommonCrypto/CommonDigest.h>
#import "TableBar.h"
#import "HomeViewController.h"
#import "RESideMenu.h"
#import "SetViewController.h"

#define BUTTONWIDTH (self.window.frame.size.width - 150) / 2.0f

@interface AppDelegate () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, RESideMenuDelegate>

@property (nonatomic, retain) UIView *cameraView;

@property (nonatomic, retain) UIVisualEffectView *visualView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    self.tb = [[TableBar alloc] init];
#pragma mark - 创建抽屉效果
    SetViewController *setVC = [[SetViewController alloc] init];
    
    RESideMenu *SideMenu = [[RESideMenu alloc] initWithContentViewController:self.tb leftMenuViewController:setVC rightMenuViewController:nil];
    SideMenu.backgroundImage = [UIImage imageNamed:@"backImage.jpeg"];
    SideMenu.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
    SideMenu.delegate = self;
    SideMenu.contentViewShadowColor = [UIColor blackColor];
    SideMenu.contentViewShadowOffset = CGSizeMake(0, 0);
    SideMenu.contentViewShadowOpacity = 0.6;
    SideMenu.contentViewShadowRadius = 12;
    SideMenu.contentViewShadowEnabled = YES;
    
    self.window.rootViewController = SideMenu;
    
#pragma mark - 处理tb的照相机点击事件
    [self.tb handleVisualViewWithBlock:^{
        [UIView animateWithDuration:0.4 animations:^{
            UIImageView *imageView =  [self.cameraView viewWithTag:100];
            imageView.transform = CGAffineTransformRotate(imageView.transform, M_PI_4);
            self.cameraView.alpha = 1;
            
            UIButton *buttonOfCamera = [self.cameraView viewWithTag:10];
            UIButton *buttonOfPhoto = [self.cameraView viewWithTag:11];
            
            buttonOfCamera.frame = CGRectMake(50, self.window.frame.size.height / 3 + 10, BUTTONWIDTH, BUTTONWIDTH);
            buttonOfPhoto.frame = CGRectMake(BUTTONWIDTH + 100, self.window.frame.size.height / 3 + 10, BUTTONWIDTH, BUTTONWIDTH);
            
        }];
    }];
    
#pragma mark - 夜间模式加载
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISNIGHT"]) {
        [DKNightVersionManager nightFalling];
    }else {
        [DKNightVersionManager dawnComing];
        
    }
    
    
#pragma mark - 引导页加载
    
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"showGuide"] boolValue]){
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"showGuide"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        FirstScrollView *first = [[FirstScrollView alloc] initWithFrame:self.window.bounds];
        [self.window addSubview:first];
        [first release];
        //创建对象
        NSFileManager *manage = [NSFileManager defaultManager];
        
        //设置文件夹路径
        NSString *dir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Cache"];
        
        //创建目录
        [manage createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
#pragma mark - 打开数据库
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"PetAPPDB.sqlite"];
    
    [[DataBaseHandle shareDataBaseHandle] open:file];
    NSLog(@"%@", NSHomeDirectory());
    //创建SQL语句.
    NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS history(number INTEGER PRIMARY KEY AUTOINCREMENT, content text)";
    [[DataBaseHandle shareDataBaseHandle] updateSQL:createTableSQL];
    
    
    

    
    [self createSubViews];

    
    [_tb release];
    [_window release];
    

    return YES;
}

#pragma mark - 创建照相机毛玻璃图层
- (void)createSubViews {
    
    self.cameraView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window addSubview:_cameraView];
    [_cameraView release];
    
    
    self.visualView = [[UIVisualEffectView alloc] init];
    [self.cameraView addSubview:_visualView];
    [_visualView release];
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:0];
    self.visualView.frame = self.cameraView.frame;
    self.visualView.effect = blur;
    self.cameraView.alpha = 0;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height - 49, self.window.frame.size.width, 49)];
    [self.cameraView addSubview:view];
    [view release];
    view.backgroundColor = [UIColor whiteColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleAlphaCameraView)];
    [view addGestureRecognizer:tap];
    [tap release];
    
    UIImageView *imageViewOfBack = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 55, 48)];
    imageViewOfBack.center = CGPointMake(self.cameraView.center.x, CGRectGetHeight(self.cameraView.frame) - 3 - 10 - 46 / 2 - 10);
    [self.cameraView addSubview:imageViewOfBack];
    imageViewOfBack.image = [UIImage imageNamed:@"yeallowBack"];
    
    
    
    
    /** 下面的关闭按钮 */
    UIImageView *imageViewOfAdd = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    [self.cameraView addSubview:imageViewOfAdd];
    [imageViewOfAdd release];
    
    imageViewOfAdd.image = [UIImage imageNamed:@"CameraAdd"];
    imageViewOfAdd.center =  CGPointMake(imageViewOfBack.center.x, imageViewOfBack.center.y + 4);
    imageViewOfAdd.tag = 100;
    
    /** 上面的文字 */
    UIView *viewOfLabel = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height / 3)];
    [self.cameraView addSubview:viewOfLabel];
    [viewOfLabel release];
    
    UILabel *labelOfText = [[UILabel alloc] initWithFrame:CGRectMake(0, viewOfLabel.center.y + 20, self.window.frame.size.width, 30)];
    [viewOfLabel addSubview:labelOfText];
    [labelOfText release];
    labelOfText.textAlignment = NSTextAlignmentCenter;
    labelOfText.textColor = [UIColor grayColor];
    labelOfText.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:22];
    labelOfText.text = @"你的时尚养宠生活！";
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleAlphaCameraView)];
    [viewOfLabel addGestureRecognizer:tap2];
    [tap2 release];
    
    /** 左面的照相机图标 */
    UIButton *buttonOfCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cameraView addSubview:buttonOfCamera];
    buttonOfCamera.frame = CGRectMake(50, self.window.frame.size.height + 100, BUTTONWIDTH, BUTTONWIDTH);
    buttonOfCamera.layer.cornerRadius = BUTTONWIDTH / 2;
    buttonOfCamera.tag = 10;
    [buttonOfCamera setImage:[UIImage imageNamed:@"xiangji"] forState:UIControlStateNormal];
    [buttonOfCamera setBackgroundColor:[UIColor colorWithRed:0.8667 green:0.2118 blue:0.4078 alpha:1.0]];
    [buttonOfCamera setImageEdgeInsets:UIEdgeInsetsMake(30, 30, 30, 30)];
    
    [buttonOfCamera addTarget:self action:@selector(handleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    /** 右侧的相册图标 */
    UIButton *buttonOfPhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cameraView addSubview:buttonOfPhoto];
    buttonOfPhoto.frame = CGRectMake(BUTTONWIDTH + 100, self.window.frame.size.height + 200, BUTTONWIDTH, BUTTONWIDTH);
    buttonOfPhoto.layer.cornerRadius = BUTTONWIDTH / 2;
    
    buttonOfPhoto.tag = 11;
    [buttonOfPhoto setImage:[UIImage imageNamed:@"xiangce"] forState:UIControlStateNormal];
    [buttonOfPhoto setBackgroundColor:[UIColor colorWithRed:0.9451 green:0.3255 blue:0.2941 alpha:1.0]];
    [buttonOfPhoto setImageEdgeInsets:UIEdgeInsetsMake(30, 30, 30, 30)];
    [buttonOfPhoto addTarget:self action:@selector(handleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

#pragma mark - 点击消失图层
- (void)handleAlphaCameraView {
    [UIView animateWithDuration:0.4 animations:^{
        UIImageView *imageView =  [self.cameraView viewWithTag:100];
        imageView.transform = CGAffineTransformRotate(imageView.transform, M_PI_4);
        self.cameraView.alpha = 0;
        
        UIButton *buttonOfCamera = [self.cameraView viewWithTag:10];
        UIButton *buttonOfPhoto = [self.cameraView viewWithTag:11];
        
        buttonOfCamera.frame = CGRectMake(50, self.window.frame.size.height, BUTTONWIDTH, BUTTONWIDTH);
        buttonOfPhoto.frame = CGRectMake(BUTTONWIDTH + 100, self.window.frame.size.height + 400, BUTTONWIDTH, BUTTONWIDTH);
    }];
    
}
#pragma mark - 处理相机和相册的点击事件
- (void)handleButtonAction:(UIButton *)button {
    [self handleAlphaCameraView];
    
    //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //    UIImagePickerControllerQualityType
    if (button.tag == 10) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }else{
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    picker.sourceType = sourceType;
    
    picker.navigationBar.barStyle = 2;
    picker.navigationBar.alpha = 0.1;
    
    [self.window.rootViewController presentViewController:picker animated:YES completion:nil];
    
    [picker release];
}

- (void)dealloc {
    [[DataBaseHandle shareDataBaseHandle] closeDB];
    [_cameraView release];
    [_visualView release];
    [_window release];
    [super dealloc];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
